package redisWriteReadSeparation;

import java.lang.reflect.Method;
import java.util.Date;

import javax.annotation.PostConstruct;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import redis.clients.jedis.JedisPool;

/**
 * @author 赵策
 * @category 此类的目的是针对主和从的注解，进行动态链接池调配，即主的使用主链接池，从的使用从连接池。
 * @param
 *
 */
@Aspect
public class JedisPoolAspect implements ApplicationContextAware {

	private ApplicationContext cx;

	@PostConstruct
	public void init() {
		System.out.println("Jedis pool aspectj started @" + new Date());
	}

	@Pointcut("execution(* redisWriteReadSeparation.*.*(..))") // 这里的注解可能会出问题
	private void allMethod() {

	}

	@Before("allMethod()")
	public void before(JoinPoint point) {
		Object target = point.getTarget();
		String method = point.getSignature().getName();

		Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
		try {
			Method m = target.getClass().getMethod(method, parameterTypes);
			if (m != null && m.isAnnotationPresent(JedisPollSelector.class)) {
				JedisPollSelector data = m.getAnnotation(JedisPollSelector.class);
				JedisPool jedisPool = (JedisPool) cx.getBean(data.value());
				DynamicJedisPoolHolder.putJedisPool(jedisPool);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		// TODO Auto-generated method stub
		this.cx = applicationContext;
	}

}
